package com.xique.park.controller.client.web.service.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xique.common.core.constant.Constants;
import com.xique.common.core.constant.UserConstants;
import com.xique.common.core.enums.UserStatus;
import com.xique.common.core.exception.BaseException;
import com.xique.common.core.utils.DateUtils;
import com.xique.common.core.utils.OrikaUtil;
import com.xique.common.core.utils.SecurityUtils;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.sign.RsaUtils;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.security.service.TokenService;
import com.xique.park.controller.client.web.bean.domain.Client;
import com.xique.park.controller.client.web.bean.domain.ClientUser;
import com.xique.park.controller.client.web.bean.domain.SysUser;
import com.xique.park.controller.client.web.bean.request.ClientChangePasswordRequest;
import com.xique.park.controller.client.web.bean.request.ClientRelieveRequest;
import com.xique.park.controller.client.web.service.biz.service.IClientLoginBizService;
import com.xique.park.controller.client.web.service.biz.service.IClientLoginInfoBizService;
import com.xique.park.controller.client.web.service.service.IClientService;
import com.xique.park.controller.client.web.service.service.IClientUserService;
import com.xique.park.controller.client.web.service.service.ISysUserService;
import com.xique.system.api.RemoteSystemLogService;
import com.xique.system.api.dto.SystemUserDTO;
import com.xique.system.api.model.LoginSystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author shd
 * @create 2021/7/31 16:22
 */
@Service
public class ClientLoginBizServiceImpl implements IClientLoginBizService {

    @Autowired
    private IClientLoginInfoBizService clientLoginInfoBizService;

    @Autowired
    private IClientService clientService;

    @Autowired
    private IClientUserService clientUserService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RemoteSystemLogService remoteSystemLogService;

    @Value("${xique.api.privateKey}")
    private String privateKey;

    /**
     * 换班登录
     * @author shd
     * @date 2021/7/31 14:01
     * @param request
     * @return com.xique.common.core.web.domain.AjaxResult
     */
    @Override
    public AjaxResult relieve(ClientRelieveRequest request) {

        Long clientId = SecurityUtils.getClientId();

        AjaxResult result = checkClientRelieveRequest(request, clientId);
        if (!AjaxResult.isSuccess(result)) {
            return result;
        }

        String loginName = request.getLoginName();
        String oldLoginName = SecurityUtils.getUsername();

        // 删除当前用户登录信息
        tokenService.delLoginUser(SecurityUtils.getToken());
        // 添加登出日志
        clientLoginInfoBizService.addLoginInfo(clientId, oldLoginName, Constants.LOGOUT, "退出成功");
        remoteSystemLogService.saveLoginInfo(oldLoginName, Constants.LOGOUT, "退出成功", UserConstants.Platform.CLIENT);

        QueryWrapper<SysUser> condition = new QueryWrapper<>();
        condition.eq("login_name", loginName);
        condition.eq("del_flag", 0);
        SysUser user = sysUserService.getOne(condition);
//        ClientUserInfo user = clientUserInfoService.selectClientUserByLoginName(loginName);
        LoginSystemUser loginClientUser = new LoginSystemUser();
        loginClientUser.setSystemUser(OrikaUtil.convert(user, SystemUserDTO.class));
        loginClientUser.setClientId(clientId);
        // 存储登录信息
        Map<String, Object> map = tokenService.createToken(loginClientUser);

        // 更新岗亭登录用户信息
        Client update = new Client();
        update.setId(clientId);
        update.setSysUserId(user.getUserId());
        update.setLoginUserName(user.getLoginName());
        update.setLoginTime(DateUtils.getNowDate());
        clientService.updateClient(update);

        // 更新用户在线离线状态
        SysUser loginInUser = new SysUser();
        loginInUser.setUserId(user.getUserId());
        loginInUser.setOnlineStatus(UserConstants.OnlineStatus.ONLINE);
        sysUserService.updateById(loginInUser);

        condition = new QueryWrapper<>();
        condition.eq("login_name", oldLoginName);
        condition.eq("del_flag", 0);
        user = sysUserService.getOne(condition);
        SysUser loginOutUser = new SysUser();
        loginOutUser.setUserId(user.getUserId());
        loginOutUser.setOnlineStatus(UserConstants.OnlineStatus.OFFLINE);
        sysUserService.updateById(loginOutUser);

        // 添加登录日志
        clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_SUCCESS, "登录成功");
        remoteSystemLogService.saveLoginInfo(loginName, Constants.LOGIN_SUCCESS, "登录成功", UserConstants.Platform.CLIENT);

        return AjaxResult.success(map);
    }

    private AjaxResult checkClientRelieveRequest(ClientRelieveRequest request, Long clientId) {

        String loginName = request.getLoginName();
        String oldLoginName = SecurityUtils.getUsername();
        String password = "";
        try {
            password = RsaUtils.decryptByPrivateKey(privateKey, request.getPassword());
        } catch (Exception e) {
            throw new BaseException("密码解析错误");
        }

        if (loginName.equals(oldLoginName)) {
            return AjaxResult.error("登录用户：" + loginName + " 已登录当前岗亭");
        }

        QueryWrapper<SysUser> condition = new QueryWrapper<>();
        condition.eq("login_name", loginName);
        SysUser user = sysUserService.getOne(condition);

//        ClientUserInfo user = clientUserInfoService.selectClientUserByLoginName(loginName);
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("登录用户：" + loginName + " 不存在");
        }
        //判断当前用户是否是该岗亭用户
        ClientUser search = new ClientUser();
        search.setSysUserId(user.getUserId());
        search.setClientId(clientId);
        ClientUser clientUser = clientUserService.selectOne(search);
        if (null == clientUser) {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "岗亭没有此用户");
            return AjaxResult.error("岗亭没有此用户");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(loginName, password))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户/密码必须填写");
            return AjaxResult.error("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            return AjaxResult.error("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
                || loginName.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户名不在指定范围");
            return AjaxResult.error("用户名不在指定范围");
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            return AjaxResult.error("对不起，您的账号：" + loginName + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            return AjaxResult.error("对不起，您的账号：" + loginName + " 已停用");
        }
        if (!SecurityUtils.matchesPasswordWithOldVersion(password, user.getLoginName(), user.getSalt(), user.getPassword()) && !SecurityUtils.matchesPassword(password, user.getPassword()))
        {
            clientLoginInfoBizService.addLoginInfo(clientId, loginName, Constants.LOGIN_FAIL, "用户密码错误");
            return AjaxResult.error("用户不存在/密码错误");
        }
        return AjaxResult.success();
    }

    /**
     * 修改密码
     * @author shd
     * @date 2021/7/31 16:34
     * @param request
     * @return com.xique.common.core.web.domain.AjaxResult
     */
    @Override
    public AjaxResult changePassword(ClientChangePasswordRequest request) {

        AjaxResult result = checkClientChangePasswordRequest(request);
        if (!AjaxResult.isSuccess(result)) {
            return result;
        }

        // 更新用户密码
        LoginSystemUser loginClientUser = tokenService.getLoginUser();
        SystemUserDTO user = loginClientUser.getSystemUser();

//        ClientUserInform update = new ClientUserInform();
//        update.setId(user.getId());
//        update.setPassword(request.getNewPassword());
//        clientUserInfoService.updateClientUser(update);

        SysUser update = new SysUser();
        update.setUserId(user.getUserId());
        update.setPassword(SecurityUtils.encryptPassword(request.getNewPassword()));
        sysUserService.updateById(update);

        // 更新redis信息
        user.setPassword(update.getPassword());
        loginClientUser.setSystemUser(user);
        tokenService.refreshToken(loginClientUser);

        return AjaxResult.success();
    }

    private AjaxResult checkClientChangePasswordRequest(ClientChangePasswordRequest request) {
        String oldPassword = "";
        try {
            oldPassword = RsaUtils.decryptByPrivateKey(privateKey, request.getOldPassword());
        } catch (Exception e) {
            throw new BaseException("原密码解析错误");
        }
        request.setOldPassword(oldPassword);
        String newPassword = "";
        try {
            newPassword = RsaUtils.decryptByPrivateKey(privateKey, request.getNewPassword());
        } catch (Exception e) {
            throw new BaseException("新密码解析错误");
        }
        request.setNewPassword(newPassword);
        if (StringUtils.isAnyBlank(oldPassword, newPassword))
        {
            return AjaxResult.error("原用户/新密码必须填写");
        }
        if (oldPassword.length() < UserConstants.PASSWORD_MIN_LENGTH
                || oldPassword.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return AjaxResult.error("用户原密码不在指定范围");
        }
        if (newPassword.length() < UserConstants.PASSWORD_MIN_LENGTH
                || newPassword.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            return AjaxResult.error("用户新密码不在指定范围");
        }
        SystemUserDTO user = tokenService.getLoginUser().getSystemUser();
        if (!SecurityUtils.matchesPasswordWithOldVersion(oldPassword, user.getLoginName(), user.getSalt(), user.getPassword()) && !SecurityUtils.matchesPassword(oldPassword, user.getPassword()))
        {
            return AjaxResult.error("原密码错误");
        }
        return AjaxResult.success();
    }
}
